import { useEffect, useState } from 'react';
import { dCityTreeListStore } from '@/business/store/city/dCity';
import { Picker } from '@tarojs/components';

interface CityDemandPickerProps {
    onRegionChange?: (value: string) => void;
    onRegionIdChange?: (id: string) => void;
    children?: (regionText: string) => React.ReactNode;
    value?: string; // 传入的省市区 ID 路径，如 "provinceId,cityId,districtId"
}

export default function CityUserPicker(props: CityDemandPickerProps) {
    // 获取地区数据
    let cityTreeList = dCityTreeListStore((state: { dCityTreeList: any; }) => state.dCityTreeList);

    // cityTreeList = [{
    //     id: '',
    //     name: '全国',
    //     demandCount: cityTreeList.reduce((acc: number, p: any) => acc + (p.demandCount || 0), 0),
    //     children: [
    //         {
    //             name: "全部", id: "", children: [
    //                 {
    //                     name: "全部",
    //                     id: "",
    //                 }
    //             ]
    //         }
    //     ]
    // }, ...cityTreeList];
    // 选择的地区文本
    const [regionText, setRegionText] = useState('');

    // 三级联动相关状态
    const [regionMultiArray, setRegionMultiArray] = useState<[string[], string[], string[]]>([[], [], []]);
    const [regionMultiIndex, setRegionMultiIndex] = useState<[number, number, number]>([0, 0, 0]);

    // 根据 ID 路径找到索引的辅助函数
    const findIndicesByIds = (ids: string[]): [number, number, number] => {
        const [provinceId, cityId, districtId] = ids;
        const provinceIdx = cityTreeList.findIndex((p: any) => p.id === provinceId);
        if (provinceIdx === -1) return [0, 0, 0];
        const cities = cityTreeList[provinceIdx]?.children || [];
        const cityIdx = cities.findIndex((c: any) => c.id === cityId);
        if (cityIdx === -1) return [provinceIdx, 0, 0];
        const districts = cities[cityIdx]?.children || [];
        const districtIdx = districts.findIndex((d: any) => d.id === districtId);
        return [provinceIdx, cityIdx, districtIdx === -1 ? 0 : districtIdx];
    };

    useEffect(() => {
        if (cityTreeList.length > 0) {
            // 拼接省份名称和用户数
            let provinces = cityTreeList.map((p: any) => `${p.name}${p.demandCount !== undefined ? `(${p.demandCount}个)` : ''}`);
            let cities: string[] = [];
            let districts: string[] = [];
            let indices: [number, number, number] = [0, 0, 0];
            let text = '';

            if (props.value) {
                const ids = props.value.split(',');
                indices = findIndicesByIds(ids);
                const [provinceIdx, cityIdx, districtIdx] = indices;
                cities = cityTreeList[provinceIdx]?.children?.map((c: any) => `${c.name}${c.demandCount !== undefined ? `(${c.demandCount}个)` : ''}`) || [];
                districts = cityTreeList[provinceIdx]?.children?.[cityIdx]?.children?.map((d: any) => `${d.name}${d.demandCount !== undefined ? `(${d.demandCount}个)` : ''}`) || [];
                const province = cityTreeList[provinceIdx];
                const city = province?.children?.[cityIdx];
                const district = city?.children?.[districtIdx];
                text = [province?.name, city?.name, district?.name].filter(Boolean).join(' ');
            } else {
                cities = cityTreeList[0]?.children?.map((c: any) => `${c.name}${c.demandCount !== undefined ? `(${c.demandCount}个)` : ''}`) || [];
                districts = cityTreeList[0]?.children?.[0]?.children?.map((d: any) => `${d.name}${d.demandCount !== undefined ? `(${d.demandCount}个)` : ''}`) || [];
            }

            setRegionMultiArray([provinces, cities, districts]);
            setRegionMultiIndex(indices);
            setRegionText(text);
        }
    }, [cityTreeList, props.value]);

    useEffect(() => {
        if (cityTreeList.length > 0) {
            const provinces = cityTreeList.map((p: any) => `${p.name}${p.demandCount !== undefined ? `(${p.demandCount}个)` : ''}`);
            const cities = cityTreeList[0]?.children?.map((c: any) => `${c.name}${c.demandCount !== undefined ? `(${c.demandCount}个)` : ''}`) || [];
            const districts = cityTreeList[0]?.children?.[0]?.children?.map((d: any) => `${d.name}${d.demandCount !== undefined ? `(${d.demandCount}个)` : ''}`) || [];
            setRegionMultiArray([provinces, cities, districts]);
        }
    }, [cityTreeList]);

    // Picker 柱变化时，动态更新下级选项
    const handleRegionColumnChange = (e: any) => {
        const column = e.detail.column;
        const value = e.detail.value;
        let newMultiIndex = [...regionMultiIndex] as [number, number, number];
        newMultiIndex[column] = value;
        if (column === 0) {
            // 省变化，更新市和区
            const cities = cityTreeList[value]?.children?.map((c: any) => `${c.name}${c.demandCount !== undefined ? `(${c.demandCount}个)` : ''}`) || [];
            const districts = cityTreeList[value]?.children?.[0]?.children?.map((d: any) => `${d.name}${d.demandCount !== undefined ? `(${d.demandCount}个)` : ''}`) || [];
            setRegionMultiArray([
                regionMultiArray[0],
                cities,
                districts,
            ]);
            newMultiIndex[1] = 0;
            newMultiIndex[2] = 0;
        } else if (column === 1) {
            // 市变化，更新区
            const provinceIdx = newMultiIndex[0];
            const citiesArr = cityTreeList[provinceIdx]?.children || [];
            const districts = citiesArr[value]?.children?.map((d: any) => `${d.name}${d.demandCount !== undefined ? `(${d.demandCount}个)` : ''}`) || [];
            setRegionMultiArray([
                regionMultiArray[0],
                regionMultiArray[1],
                districts,
            ]);
            newMultiIndex[2] = 0;
        }
        setRegionMultiIndex(newMultiIndex);
    };

    // Picker 选中后，展示地区名称并回调拼接好的省市区
    const handleRegionChange = (e: any) => {
        const [provinceIdx, cityIdx, districtIdx] = e.detail.value;
        setRegionMultiIndex([provinceIdx, cityIdx, districtIdx]);
        const province = cityTreeList[provinceIdx];
        const city = province?.children?.[cityIdx];
        const district = city?.children?.[districtIdx];
        const text = [province?.name, city?.name, district?.name].filter(Boolean).join(' ');
        setRegionText(text);
        props.onRegionChange?.(text);
        console.log('texttexttexttext', text);
        const ids = [province, city, district].map(item => item?.name !== '全部' ? item?.id : null).filter(Boolean);
        let id = ids.join(',');
        if (id) {
            const parts = id.split(',');
            if (parts.length === 1) {
                id = parts.slice(0).join(',');
            } else if (parts.length === 2) {
                id = parts.slice(1).join(',');
            } else if (parts.length === 3) {
                id = parts.slice(2).join(',');
            }
        }
        console.log(id, 'id')
        props.onRegionIdChange?.(id);
    };
    return (
        <Picker
            mode='multiSelector'
            range={regionMultiArray}
            value={regionMultiIndex}
            onChange={handleRegionChange}
            onColumnChange={handleRegionColumnChange}
        >
            {props.children ? props.children(regionText) : null}
        </Picker>
    );
}
